const db = require("../../db/index");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("../../config/config");
const login = (req, res) => {
  const userinfo = req.body;
  const sql = `select * from en_users where username=?`;
  db.query(sql, userinfo.username, (err, result) => {
    if (err) return res.cc(err);
    if (result.length !== 1) return res.cc("登录失败");
    const compareResult = bcrypt.compareSync(
      userinfo.password,
      result[0].password
    );
    console.log(compareResult);
    if (!compareResult) {
      return res.cc("登录失败");
    }
    const user = { ...result[0], password: "", user_pic: "" };
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {
      expiresIn: "10h",
    });
    res.send({
      status: 0,
      msg: "登录成功",
      code: 200,
      token: "Bearer " + tokenStr,
    });
  });
};
const reguser = (req, res) => {
  const userinfo = req.body;
  if (!userinfo.username || !userinfo.password) {
    return res.send({
      status: 1,
      msg: "用户名或密码不能为空",
    });
  }
  const sql1 = `select * from en_users where username=?`;
  db.query(sql1, [userinfo.username], (err, result) => {
    if (err) {
      return res.send({
        satus: 1,
        msg: err.message,
      });
    }
    if (result.length > 0) {
      return res.send({
        status: 1,
        msg: "用户名被占用",
      });
    }
  });
  userinfo.password = bcrypt.hashSync(userinfo.password, 10);
  const sql2 = "insert into en_users set?";
  db.query(
    sql2,
    { username: userinfo.username, password: userinfo.password },
    (err, result) => {
      if (err) return console.log({ status: 1, msg: err.message });
      if (result.affectedRows !== 1) {
        return res.send({ status: 1, message: "注册用户失败，请稍后再试！" });
      }
      // 注册成功
      res.send({ status: 0, message: "注册成功！" });
    }
  );
};
module.exports = {
  login: login,
  reguser: reguser,
};
